<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top:10px">
      <el-row>
        <el-col :span="8">
          <!-- 使用双向绑定实现搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" class="buttoncol">
          <el-button
            type="primary"
            style="margin-left: 10%;"
            @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户数据表格 -->
      <el-table
        :data="userList"
        border
        style="width: 100%;margin-top:20px;text-align:center;"
      >
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @click="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top:10px"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="60%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="60%"
      @close = "setCloseRoles"
    >
      <div>
        <p>用户名称：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校验规则，验证邮箱
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback();
      }
      // 错误邮箱
      callback(new Error("请输入正确的邮箱"));
    };
    // 校验规则，验证手机号
    var checkMobile = (rule, value, callback) => {
      // 验证手机号 规则
      const regMobile = /^(0|86}17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        // 合法手机号
        return callback();
      }
      callback(new Error("请输入正确的手机号"));
    };

    return {
      // 添加用户
      addDialogVisible: false,
      // 修改用户信息
      editDialogVisible: false,
      // 获取请求参数
      queryInfo: {
        // 双向绑定关键字
        query: "",
        pagenum: 1,
        // 当前每页显示多少套数据
        pagesize: 2
      },
      // 修改用户表单
      editForm: {},
      userList: [],
      total: "",
      radio: "1",
      // 需要被分配角色的用户信息
      userInfo: {},
      // 控制分配角色
      setRoleDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 角色列表
      rolesList: [],
      // 被选中的角色id
      selectedRoleId:'',
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, trigger: "blur", message: "用户名长度在3到10之间" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, trigger: "blur", message: "密码长度在6到18之间" }
        ],
        email: [
          { required: true, message: "请输入邮箱号", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 修改用户信息的校验规则
      editFormRules: {
        email: [
          { required: true, message: "请输入正确的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      // 请求携带的参数放在params里面
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.console.error("获取用户列表失败！");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log(res);
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听switch状态
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status != 200) {
        this.$message.error("用户状态更新失败");
        userinfo.mg_state != userinfo.mg_state;
      }
      this.$message.success("用户状态更新成功！");
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs.addFormRef.resetFields();
    },
    // 添加新用户
    addUser() {
      // 预校验
      this.$refs.addFormRef.validate(async valid => {
        // 失败
        if (!valid) return;
        // 成功
        const { data: res } = await this.$http.post("users", this.addForm);

        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }

        this.$message.success("添加成功");
        // 关闭对话框
        this.addDialogVisible = false;
        // 刷新源数据列表
        this.getUserList();
      });
    },
    // 修改用户信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error("获取用户失败");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 重置修改表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    eidtUserInfo() {
      // 预验证
      this.$refs.editFormRef.validate(async valid => {
        // 预验证失败
        if (!valid) return;
        // 预验证成功
        // 1.发起数据请求
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        );
        // 对请求数据结果进行判断
        if (res.meta.status !== 200) {
          return this.$message.error("用户数据提交失败！");
        }
        // 提交成功
        /**
         * 1.关闭对话框
         * 2.刷新数据
         * 3.提示
         */
        this.editDialogVisible = false;
        this.getUserList();
        this.$message.success("修改数据成功！");
      });
    },
    // 根据id删除数据
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
          // 箭头函数缩写，如果只有一行代码，可以省略花括号和return
        }
      ).catch(err => err);
      // 点击了取消
      if (confirmResult !== "confirm") {
        return this.$message.info("您取消了删除！");
      }
      // 点击了确定
      // 1.调用api接口
      const { data: res } = await this.$http.delete("users/" + id);
      // 2.判断删除是否成功
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      // 2.删除成功
      // 2.1 提示删除成功
      // 2.2 更新用户列表
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
    // 分配角色
    async setRole(userInfo) {
      this.userInfo = userInfo;
      // 在展示对话框之前，先获取角色列表
      const { data: res } = await this.$http.get("roles");
      // 请求失败
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      // 把角色列表保存在数组中
      this.rolesList = res.data;
      this.setRoleDialogVisible = true;
    },
    // 提交角色
    async  saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error('请分配角色')
      }
      // 发起数据请求
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid: this.selectedRoleId
      })
      // 请求失败
      if(res.meta.status !== 200){
        return this.$message.error('分批新角色失败')
      }

      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false
        
      

    },
    // 对分配角色对话框关闭时的监听
    setCloseRoles(){
      this.selectedRoleId = ''
      this.userInfo = []
    }
  }
};
</script>

<style>
</style>